package com.echoesnet.echoesshortvideo.Fragments;

import android.app.Activity;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.PointF;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.view.animation.ScaleAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.ImageViewState;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.echoesnet.echoesshortvideo.Activities.CUserInfoAct;
import com.echoesnet.echoesshortvideo.Activities.FanAndFocusAct;
import com.echoesnet.echoesshortvideo.Activities.PlayVideoActivity;
import com.echoesnet.echoesshortvideo.Activities.ReportFoulsUserAct;
import com.echoesnet.echoesshortvideo.AppController;
import com.echoesnet.echoesshortvideo.Beans.UserBean;
import com.echoesnet.echoesshortvideo.Constant.CommonConstant;
import com.echoesnet.echoesshortvideo.R;
import com.echoesnet.echoesshortvideo.Utils.CommonUtils;
import com.echoesnet.echoesshortvideo.Utils.Image.GlideApp;
import com.echoesnet.echoesshortvideo.Utils.ImageUtils.ImageUtils;
import com.echoesnet.echoesshortvideo.Utils.SharePreUtils;
import com.echoesnet.echoesshortvideo.Utils.ToastUtils;
import com.echoesnet.echoesshortvideo.View.BottomSelector;
import com.echoesnet.echoesshortvideo.View.smoothImageView.SmoothImageView;
import com.echoesnet.echoesshortvideo.ViewModels.FansFocusViewModel;
import com.echoesnet.echoesshortvideo.ViewModels.UserDetailViewModel;
import com.echoesnet.echoesshortvideo.views.dialog.CustomAlertDialog;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * @author yqh
 * @Date 2018/4/23
 * @Version 1.0
 */
public class UserInfoFragment extends BaseFragment
{
    private final String TAG = UserInfoFragment.class.getSimpleName();
    @BindView(R.id.userHeader)
    ImageView userHeader;
    @BindView(R.id.userHeaderSc)
    ImageView userHeaderSc;
    @BindView(R.id.userHeaderSc_layout)
    FrameLayout imageFl;
    @BindView(R.id.sendMessage)
    TextView sendMessage;
    @BindView(R.id.infoMore)
    TextView infoMore;
    @BindView(R.id.infoUsername)
    TextView infoUsername;
    @BindView(R.id.infoUserId)
    TextView infoUserId;
    @BindView(R.id.infoUserIdContent)
    TextView infoUserIdContent;
    @BindView(R.id.infoUserLocation)
    TextView infoUserLocation;
    @BindView(R.id.infoUserGender)
    TextView infoUserGender;
    @BindView(R.id.infoUserXingzuo)
    TextView infoUserXingzuo;
    @BindView(R.id.userInfoContent)
    LinearLayout userInfoContent;
    @BindView(R.id.room_layout)
    RelativeLayout roomLayout;
    @BindView(R.id.infoFansNum)
    TextView infoFansNum;
    @BindView(R.id.infoFocusNum)
    TextView infoFocusNum;
    @BindView(R.id.infoPraiseNum)
    TextView infoPraiseNum;
    @BindView(R.id.signature)
    TextView signature;
    @BindView(R.id.userHeaderCover)
    ImageView userHeaderCover;
    @BindView(R.id.infoFansContent)
    TextView infoFansContent;
    @BindView(R.id.infoFocusContent)
    TextView infoFocusContent;
    @BindView(R.id.infoPraiseContent)
    TextView infoPraiseContent;
    @BindView(R.id.iv_infoUserGender)
    ImageView ivInfoUserGender;
    @BindView(R.id.ll_all_gender)
    LinearLayout llAllGender;

    private Activity mActivity;
    private UserDetailViewModel uViewModel;
    private FansFocusViewModel lModel;
    private String status = "";

    private UserBean userBean;
    private int finishResult = 2;
    private Unbinder unbinder;
    private MyVideoListFrg videoListFrg;
    private String uId = "";
    private String isBlack = "0";
    private List<String> lHeadUrl = new ArrayList<String>();
    private boolean isShowImage=true;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
    {
        View view = inflater.inflate(R.layout.user_info, container, false);
        unbinder = ButterKnife.bind(this, view);

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState)
    {
        super.onViewCreated(view, savedInstanceState);

        afterViews();

    }

    public static UserInfoFragment newUserInfoFrg(@Nullable String luid, String activity, int position)
    {
        Bundle bundle = new Bundle();
        bundle.putString("uId", luid);
        bundle.putString("Activity", activity);
        bundle.putInt("position", position);
        UserInfoFragment frg = new UserInfoFragment();
        frg.setArguments(bundle);
        return frg;
    }

    @Override
    public void onResume()
    {
        super.onResume();
        //这边刷新会闪烁
//        if (!TextUtils.isEmpty(uId))
//        {
//            if (uViewModel != null)
//                uViewModel.requestUserDetail(uId);
//        }
    }

    private void afterViews()
    {
        mActivity = getActivity();
        uViewModel = ViewModelProviders.of(this).get(UserDetailViewModel.class);
        registerIntentFilter();

        videoListFrg = MyVideoListFrg.newVideoListFrg("uid");
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.replace(R.id.video_layout, videoListFrg);
        transaction.commit();
        uViewModel.getUserDetail().observe(this, userBean ->
        {
            if (userBean != null)
            {
                Logger.t(TAG).d("USER:" + userBean.toString());
                setUserInfo(userBean);


                if (videoListFrg!=null)
                {
                    videoListFrg.requestMyVideosList(uId);
                }
            }
        });

        lModel = ViewModelProviders.of(UserInfoFragment.this).get(FansFocusViewModel.class);
        lModel.getResultDetail().observe(this, new Observer<String>()
        {
            @Override
            public void onChanged(@Nullable String s)
            {
                if (s != null)
                {
                    if (s.equals("pullBlack"))
                    {
                        ToastUtils.showShort("拉黑成功");
                        isBlack = "1";
                    }
                    else if (s.equals("removeBlackok"))
                    {
                        ToastUtils.showShort("移除黑名单成功");
                        isBlack = "0";
                    }
                    else
                    {
                        status = s;
                        ToastUtils.showShort("关注成功");
                        sendMessage.setText("发消息");
                        sendMessage.setBackgroundResource(R.drawable.send_message);
                        Intent intent = new Intent(CommonConstant.EAM_BRD_ACTION_FOCUS_HIDE);
                        intent.putExtra("userId", userBean.getUserId());
                        mActivity.sendBroadcast(intent);
                    }

                }
            }
        });


        if (getArguments() != null)
        {
            String info = getArguments().getString("Activity");
            if (!TextUtils.isEmpty(info) && info.equals("Activity"))
            {
                if (uViewModel != null)
                    uViewModel.requestUserDetail(getArguments().getString("uId"));
                uId = getArguments().getString("uId");
            }
        }

    }

    private void registerIntentFilter()
    {
        IntentFilter filter = new IntentFilter();
        filter.addAction(CommonConstant.EAM_BRD_ACTION_REQUEST_USERINFO);
        filter.addAction(CommonConstant.EAM_BRD_ACTION_FOCUS_HIDE);
        filter.addAction(CommonConstant.EAM_BRD_ACTION_FOCUS_SHOW);
        mActivity.registerReceiver(receiver, filter);
    }

    private void unRegisterIntentFilter()
    {
        if (receiver != null)
            mActivity.unregisterReceiver(receiver);
    }

    BroadcastReceiver receiver = new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            switch (intent.getAction())
            {
                case CommonConstant.EAM_BRD_ACTION_REQUEST_USERINFO:
                    String otherId = intent.getStringExtra("otherUserId");
                    uId = otherId;
                    if (uViewModel != null)
                        uViewModel.requestUserDetail(otherId);
                    break;
                case CommonConstant.EAM_BRD_ACTION_FOCUS_SHOW://未关注
                    sendMessage.setText("关注");
                    sendMessage.setBackgroundResource(R.drawable.follow_round);
                    break;
            }
        }
    };

    public void refreshFocusState()
    {
        sendMessage.setText("发消息");
        sendMessage.setBackgroundResource(R.drawable.send_message);

        if (userBean != null)
        {
            int shareNum;
            try
            {
                shareNum = Integer.parseInt(infoFansNum.getText().toString());
                infoFansNum.setText(++shareNum + "");
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }


    public void setUserInfo(UserBean user)
    {
        if (user != null)
        {
            Logger.t(TAG).d(user.toString());
            userBean = user;
            infoUsername.setText(user.getNickname());
            infoUserIdContent.setText(user.getUserId());
            if (TextUtils.isEmpty(user.getCity()))
                infoUserLocation.setVisibility(View.GONE);
            else
                infoUserLocation.setText(user.getCity());

            if (TextUtils.isEmpty(user.getConstellation()))
                infoUserXingzuo.setVisibility(View.GONE);
            else
                infoUserXingzuo.setText(user.getConstellation());

            if (!TextUtils.isEmpty(user.getSignature()))
                signature.setText(user.getSignature());

//            if (!TextUtils.isEmpty(user.getAge()))
//                infoUserGender.setText(user.getAge());


            if (TextUtils.isEmpty(user.getAge()) && TextUtils.isEmpty(user.getSex()))
            {
                llAllGender.setVisibility(View.GONE);
            }
            else
            {
                llAllGender.setVisibility(View.VISIBLE);
                infoUserGender.setText(user.getAge());
                ivInfoUserGender.setBackgroundResource("男".equals(user.getSex()) ? R.drawable.but_man : R.drawable.but_woman);
                llAllGender.getChildAt(0).setVisibility(TextUtils.isEmpty(user.getSex()) ? View.GONE : View.VISIBLE);
                llAllGender.getChildAt(1).setVisibility(TextUtils.isEmpty(user.getAge()) ? View.GONE : View.VISIBLE);
            }
//            if (!TextUtils.isEmpty(user.getSex()))
//                infoUserGender.setText("男".equals(user.getSex()) ? " ♂ " + user.getAge() : " ♀ " + user.getAge());
//            if (TextUtils.isEmpty(user.getAge()) && TextUtils.isEmpty(user.getSex()))
//                infoUserGender.setVisibility(View.GONE);

            if (user.getUserId().equals(SharePreUtils.getUId()))
            {
                sendMessage.setVisibility(View.GONE);
                infoMore.setVisibility(View.GONE);
            }

            if ("0".equals(user.getFollowOrNot()))
            {
                sendMessage.setText("关注");
                sendMessage.setBackgroundResource(R.drawable.follow_round);
            }
            else
            {
                sendMessage.setText("发消息");
                sendMessage.setBackgroundResource(R.drawable.send_message);
            }
            status = user.getFollowOrNot();

            lHeadUrl.clear();
            lHeadUrl.add(user.getHeadPic());
            GlideApp.with(AppController.getInstance())
                    .load(user.getHeadPic())
                    .error(R.drawable.default_160px)
                    .circleCrop()
                    //   .apply(RequestOptions.bitmapTransform(new GlideRoundTransform(AppController.getInstance(),360)))
                    .into(userHeader);

            GlideApp.with(AppController.getInstance())
                    .load(user.getHeadPic())

                    .error(R.drawable.default_160px)
                    .fitCenter()
                    //   .apply(RequestOptions.bitmapTransform(new GlideRoundTransform(AppController.getInstance(),360)))
                    .into(userHeaderSc);

//            ImageUtils.showLoadingCover(mActivity, user.getHeadPic(), 6, userHeaderCover, false);
            ImageUtils.newShowLoadingCover(user.getHeadPic(), userHeaderCover);

            infoFansNum.setText(user.getFans());
            infoFocusNum.setText(user.getFollow());
            infoPraiseNum.setText(user.getLikes());

            isBlack = user.getInBlack();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser)
    {
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    protected String getPageName()
    {
        return TAG;
    }

    @Override
    public void onDestroyView()
    {
        super.onDestroyView();
        unRegisterIntentFilter();
        if (unbinder != null)
            unbinder.unbind();

    }


    private void initPopWindow()
    {
        String[] strArray;
        if (isBlack.equals("0"))
            strArray = new String[]{"拉黑", "举报"};
        else
            strArray = new String[]{"移出拉黑", "举报"};


        new BottomSelector(mActivity, Arrays.asList(strArray))
                .setFirstClickListener(new BottomSelector.OnItemClickListener()
                {
                    @Override
                    public void onItemClick(View view, BottomSelector pop)
                    {
                        if (CommonUtils.checkUserStateFromFragment(UserInfoFragment.this, TAG))
                        {
                            if (isBlack.equals("0"))
                            {
                                new CustomAlertDialog(mActivity)
                                        .builder()
                                        .setCancelable(true)
                                        .setMsg("拉黑后，Ta将无法给你发送消息\nTa的视频不会出现在首页")
                                        .setPositiveButton("取消", v ->
                                        {

                                        })
                                        .setNegativeButton("确认", v ->
                                        {
                                            if (CommonUtils.checkUserStateFromFragment(UserInfoFragment.this, null))
                                                lModel.requestPullBlack(uId);
                                        }).setNegativeTextColor(ContextCompat.getColor(getActivity(), R.color.black)).
                                        setPositiveTextColor(ContextCompat.getColor(getActivity(), R.color.black))
                                        .show();
                            }
                            else
                            {
                                if (CommonUtils.checkUserStateFromFragment(UserInfoFragment.this, null))
                                    lModel.removeBlack(uId);
                            }

                        }
                        pop.dismiss();
                    }
                })
                .setSecondClickListener(new BottomSelector.OnItemClickListener()
                {
                    @Override
                    public void onItemClick(View view, BottomSelector pop)
                    {
                        pop.dismiss();
                        if (CommonUtils.checkUserStateFromFragment(UserInfoFragment.this, TAG))
                        {
                            Intent intent = new Intent(getActivity(), ReportFoulsUserAct.class);
                            intent.putExtra("uId", uId);
                            startActivity(intent);
                        }
                    }
                }).show(roomLayout);
    }

    private Handler handler=new Handler();
    @OnClick({R.id.btBack, R.id.userHeader, R.id.sendMessage, R.id.infoMore, R.id.infoFansContent,
            R.id.infoFansNum, R.id.infoFocusContent, R.id.infoFocusNum, R.id.infoPraiseContent, R.id.infoPraiseNum, R.id.userHeaderSc})
    public void onViewClicked(View view)
    {
        switch (view.getId())
        {
            case R.id.btBack:
                if (clickListener != null)
                    clickListener.onLeftBackClick(status, getActivity().getIntent().getIntExtra("position", 0));
                break;
               case R.id.userHeader:
                   showBigHead();
                break;
                case R.id.userHeaderSc:
                    if(!isShowImage)
                    showBigHead();
                break;
            case R.id.sendMessage:
                if ("关注".equals(sendMessage.getText().toString()))
                {
                    if (CommonUtils.checkUserStateFromFragment(UserInfoFragment.this, null))
                    {
                        lModel.requestFollow(uId);
                    }
                }
                else
                {
                    ToastUtils.showShort("敬请期待...");
                }

                break;
            case R.id.infoMore:
                initPopWindow();
                break;

            case R.id.infoFansContent:
            case R.id.infoFansNum://粉丝数
                Intent fanIntent = new Intent(getActivity(), FanAndFocusAct.class);
                fanIntent.putExtra("type", "fan");
                fanIntent.putExtra("tId", uId);
                startActivity(fanIntent);
                break;
            case R.id.infoFocusContent:
            case R.id.infoFocusNum://关注数
                Intent editIntent = new Intent(getActivity(), FanAndFocusAct.class);
                editIntent.putExtra("type", "follow");
                editIntent.putExtra("tId", uId);
                startActivity(editIntent);
                break;
            case R.id.infoPraiseContent:
            case R.id.infoPraiseNum://点赞数
                break;
        }
    }


    //endregion

    private ClickListener clickListener;

    public void setClickListener(ClickListener listener)
    {
        clickListener = listener;
    }

    public void loadUserInfo(String otherUid)
    {
        uId = otherUid;
        if (uViewModel != null)
            uViewModel.requestUserDetail(otherUid);
    }

    public interface ClickListener
    {
        void onLeftBackClick(String state, int position);
    }

    private IOnUserInfoActionListener userInfoActionListener;

    public interface IOnUserInfoActionListener
    {
        void onFocus();
    }

    public void setOnUserInfoActionListener(IOnUserInfoActionListener listener)
    {
        userInfoActionListener = listener;
    }

    public boolean backListener()
    {
        if(getActivity() instanceof CUserInfoAct)
        {
            Intent data = new Intent();
            data.putExtra("focusStatus", status);
            int position = getActivity().getIntent().getIntExtra("position", 0);
            data.putExtra("position", position);
            getActivity().setResult(finishResult, data);
        }

        if(userHeaderSc.getVisibility()==View.VISIBLE)
        {
            showBigHead();
            return true;
        }
        else
        {
            return false;
        }
    }


    private void showBigHead()
    {
        if(!isShowImage)
        {
            isShowImage=true;
            userHeaderSc.startAnimation(AnimationUtils.loadAnimation(mActivity,R.anim.image_scale_small));
            imageFl.startAnimation(AnimationUtils.loadAnimation(mActivity,R.anim.imagebg_scale_small));
            handler.postDelayed(()->{
                userHeaderSc.setVisibility(View.GONE);
                imageFl.setVisibility(View.GONE);
                },250);
            if(getActivity() instanceof PlayVideoActivity)
                ((PlayVideoActivity) getActivity()).setHorizontalViewPagerScroll(false);
        }else
            {
                isShowImage=false;
                userHeaderSc.setVisibility(View.VISIBLE);
                imageFl.setVisibility(View.VISIBLE);
                userHeaderSc.startAnimation(AnimationUtils.loadAnimation(mActivity,R.anim.image_scale));
                imageFl.startAnimation(AnimationUtils.loadAnimation(mActivity,R.anim.imagebg_scale));
                handler.postDelayed(()->{
                    isShowImage=false;
                },250);

                if(getActivity() instanceof PlayVideoActivity)
                    ((PlayVideoActivity) getActivity()).setHorizontalViewPagerScroll(true);
            }

    }

}
